package com.sanerzone.smscenter.biz.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.cache.AccountCacheHelper;
import com.sanerzone.smscenter.biz.entity.SmsReceive;
import com.sanerzone.smscenter.biz.entity.SmsSend;
import com.sanerzone.smscenter.biz.mapper.SmsReceiveMapper;
import com.sanerzone.smscenter.biz.mapper.SmsSendMapper;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSReplyMessage;
import com.sanerzone.smscenter.biz.utils.DateHelper;
import com.sanerzone.smscenter.biz.utils.MessageExtUtil;
import com.sanerzone.smscenter.biz.utils.TableNameHelper;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.common.tools.MQHelper;
import com.sanerzone.smscenter.common.tools.SpringContextHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 网关上行
 */
@Service
public class SMSMORESListener implements MessageListenerConcurrently {
	private Logger logger = LoggerFactory.getLogger(SMSMORESListener.class);


	@Autowired
	private SmsSendMapper smsSendMapper;

	@Autowired
	public MQHelper mQUtils;

	@Autowired
	private SmsReceiveMapper smsReceiveMapper;

	@Override
	public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
													ConsumeConcurrentlyContext context) {
		SqlSession sqlSession = SpringContextHelper.getBean(SqlSessionFactory.class).openSession(ExecutorType.BATCH, false);
		try {
			for (MessageExt msg : msgs) {
				if (msg.getReconsumeTimes() > 2 ) {
					continue;
				}
				logger.info("SMSMORES msgid:{}, key:{}", msg.getMsgId(), msg.getKeys());
				SMSMOMessage message = MessageExtUtil.convertMessageExt(SMSMOMessage.class, msg);
				if (null == message) {
					continue;
				}
				if (StringUtils.isNotBlank(message.getPhone())) {
					Map<String, Object> map = Maps.newHashMap();
					map.put("phone", message.getPhone());
					map.put("tableName", "sms_send_" + TableNameHelper.getTableIndex(0));
					map.put("orderby","create_time");
					//把今天发过给这个号码的所有短信全都找出来。循环去调用
					List<SmsSend> list = new ArrayList<>();
					List<SmsSend>	tadayList =	smsSendMapper.findPageByPhone(map);
					if (tadayList != null && tadayList.size() > 0) {
						list.addAll(tadayList);
					}

					map.put("tableName", "sms_send_" + TableNameHelper.getTableIndex(-1));
					List<SmsSend> yList = smsSendMapper.findPageByPhone(map);
					if (yList != null && yList.size() > 0) {
						list.addAll(yList);
					}
					StringBuilder moResult = new StringBuilder();//初始化定义推送结果为空串
					String result = "";//初始化定义推送结果为空串
					int moPushFlag=0;//初始化定义为推送失败的flag
					int moAccountPushFlag=0;//初始化定义为推送失败的flag
					for (SmsSend smsSend : list) {
						List<Map<String, Object>> rList = Lists.newArrayList();
						Map<String,Object> moMap = Maps.newHashMap();
						moMap.put("mobile", list.get(0).getPhone());
						moMap.put("content", URLEncoder.encode(message.getMsgContent(),"utf-8"));
						moMap.put("taskid", msg.getMsgId());
						moMap.put("time", DateHelper.getDate("yyyyMMddHHmmss"));
						rList.add(moMap);//找smssend

						String upUrl = AccountCacheHelper.getStringValue(smsSend.getUserid() + "_" + smsSend.getAccId(), "upUrl", "");
						if (!Strings.isNullOrEmpty(upUrl)) {//能够成功发送回复短信
							 result = HttpRequest.sendPostJson(upUrl, JSON.toJSONString(rList), null, 3000);// 推送
							logger.info("上行推送，用户:{},上行地址：{}，推送内容：{}，手机号码：{},返回结果：{}", smsSend.getUserid(), upUrl, JSON.toJSONString(moMap),smsSend.getPhone(),result);
							if (StringUtils.equals("0",result) || StringUtils.equals("200",result) || StringUtils.equalsIgnoreCase("success",result)) {
								moAccountPushFlag = 1;
								moPushFlag = 1;//已推送
							}else {
								moAccountPushFlag = 2;
								moPushFlag = 2;//已推送
							}
						} else {
							moPushFlag = 0;
						}
						moResult = moResult.append(smsSend.getUserid()).append(":").append(result).append(",");
						SMSMOMessage moAccountMessage = new SMSMOMessage();
						BeanUtils.copyProperties(message, moAccountMessage);
						moAccountMessage.setPushFlag(moAccountPushFlag);
						moAccountMessage.setResult(result);
						moAccountMessage.setUserid(Integer.parseInt(smsSend.getUserid()));
						mQUtils.sendReplySMS( moAccountMessage.getMsgid(), moAccountMessage);
					}
					if (!Strings.isNullOrEmpty(moResult.toString())) {
						message.setResult(moResult.substring(0,moResult.length()-1));
					}
					message.setPushFlag(moPushFlag);
					message.setMsgid(msg.getMsgId());
					smsReceiveMapper.insertMOSmsReceive(message);
				}else{
					logger.error( "上行号码为空!" );
				}
			}
			logger.info("MORES处理完成!");
		} catch (Exception e) {
			logger.error("MORES-ERR: {}", e);
			return ConsumeConcurrentlyStatus.RECONSUME_LATER;
		}
		return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
	}

	/**
	 * 转换
	 * @param pushFlag
	 * @param result
	 * @return
	 */
	public SMSReplyMessage convertSms2SmsReply(int pushFlag,String result,SMSMOMessage msg){
		SMSReplyMessage smsReplyMessage = new SMSReplyMessage();
		BeanUtils.copyProperties(msg,smsReplyMessage);
		smsReplyMessage.setResult(result);
		smsReplyMessage.setPushFlag(pushFlag);
		smsReplyMessage.setCreatetime(new Date());
		return smsReplyMessage;
	}


	public String  aa() {
		return "";
	}
}
